package cn.iocoder.yudao.module.wrzj.controller.app.wrzjuser;

import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.module.wrzj.controller.app.BaseWrzjController;
import cn.iocoder.yudao.module.wrzj.controller.app.greatman.vo.GreatmanScore;
import cn.iocoder.yudao.module.wrzj.controller.app.wrzjuser.vo.AppWrzjUserRespVO;
import cn.iocoder.yudao.module.wrzj.controller.app.wrzjuser.vo.AppWrzjUserSaveReqVO;
import cn.iocoder.yudao.module.wrzj.dal.dataobject.greatman.GreatmanDO;
import cn.iocoder.yudao.module.wrzj.dal.dataobject.wrzjuser.WrzjUserDO;
import cn.iocoder.yudao.module.wrzj.service.conversation.ConversationService;
import cn.iocoder.yudao.module.wrzj.service.greatman.GreatmanService;
import cn.iocoder.yudao.module.wrzj.service.wrzjuser.WrzjUserService;
import com.alibaba.fastjson.JSONObject;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.NoSuchElementException;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
import static cn.iocoder.yudao.module.wrzj.enums.ErrorCodeConstants.GREATMAN_HAS_OWNED;
import static cn.iocoder.yudao.module.wrzj.enums.ErrorCodeConstants.GREATMAN_SCORE_NOT_ENOUGH;

@Tag(name = "用户 APP - 伟人之家-用户")
@RestController
@RequestMapping("/wrzj/user")
@Validated
public class AppWrzjUserController extends BaseWrzjController {

    @Resource
    private WrzjUserService userService;
    @Resource
    private GreatmanService greatmanService;
    @Resource
    private ConversationService conversationService;


    @PostMapping("/app-register")
    @Operation(summary = "app用户注册")
    public CommonResult<AppWrzjUserRespVO> userAppRegister(@Valid @RequestBody AppWrzjUserSaveReqVO createReqVO) {
        WrzjUserDO wrzjUserDO = userService.createUser(createReqVO);
        AppWrzjUserRespVO appWrzjUserRespVO = BeanUtils.toBean(wrzjUserDO, AppWrzjUserRespVO.class);
        appWrzjUserRespVO.setToken(generateUserToken(String.valueOf(wrzjUserDO.getId())));
        return success(appWrzjUserRespVO);
    }

    @PostMapping("/app-login")
    @Operation(summary = "app用户登录")
    public CommonResult<AppWrzjUserRespVO> userAppLogin(@Valid @RequestBody AppWrzjUserSaveReqVO createReqVO) {
        WrzjUserDO wrzjUserDO = userService.appUserLogin(createReqVO);
        AppWrzjUserRespVO appWrzjUserRespVO = BeanUtils.toBean(wrzjUserDO, AppWrzjUserRespVO.class);
        appWrzjUserRespVO.setToken(generateUserToken(String.valueOf(wrzjUserDO.getId())));
        return success(appWrzjUserRespVO);
    }

    @Deprecated
    @PostMapping("/login")
    @Operation(summary = "登录用户")
    public CommonResult<WrzjUserDO> userLogin(@Valid @RequestBody AppWrzjUserSaveReqVO createReqVO) {

        return success(userService.createUser(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新用户")
    public CommonResult<WrzjUserDO> updateUser(@Valid @RequestBody AppWrzjUserSaveReqVO updateReqVO) {
        userService.updateUser(updateReqVO);
        return success(userService.getUser(updateReqVO.getId()));
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除用户")
    @Parameter(name = "id", description = "编号", required = true)
    public CommonResult<Boolean> deleteUser(@RequestParam("id") Long id) {
        userService.deleteUser(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得用户")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    public CommonResult<AppWrzjUserRespVO> getUser(@RequestParam("id") Long id) {
        WrzjUserDO user = userService.getUser(id);
        return success(BeanUtils.toBean(user, AppWrzjUserRespVO.class));
    }

    @GetMapping("/statistics")
    @Operation(summary = "个人中心-数据统计")
    public CommonResult<JSONObject> statistics() {
        WrzjUserDO user = userService.getUser(getLoginUid());
        List<GreatmanScore> greatmanScoreList = JSONObject.parseArray(user.getScore(), GreatmanScore.class);
        //最喜欢的
        GreatmanScore bestlovedGreatmanScore = greatmanScoreList.stream()
                .max(Comparator.comparingInt(GreatmanScore::getScore))
                .orElseThrow(NoSuchElementException::new);
        //最不受喜欢的
        GreatmanScore lowestLovedGreatmanScore = greatmanScoreList.stream()
                .min(Comparator.comparingInt(GreatmanScore::getScore))
                .orElseThrow(NoSuchElementException::new);
        //已召唤伟人数
        long ownedCount = greatmanScoreList.stream().filter(GreatmanScore::isOwned).count();

        JSONObject jsonObject = new JSONObject();
//        jsonObject.put("challenge", "庄子");//最想挑战的伟人
        GreatmanDO bestlovedGreatman = greatmanService.getGreatman(bestlovedGreatmanScore.getId().intValue());
        JSONObject chatTimeWordsStatistics = conversationService.statisticsConversation(convertConversationId(String.valueOf(bestlovedGreatman.getId())));

        jsonObject.put("bestloved", bestlovedGreatman.getName());//最想喜欢的伟人
        jsonObject.put("period", bestlovedGreatman.getYear());//最希望生活的时代
        jsonObject.put("chat_times", chatTimeWordsStatistics.get("chat_times"));//聊天次数
        jsonObject.put("chat_words", chatTimeWordsStatistics.get("chat_words"));//聊天总计字数
        GreatmanDO lowestlovedGreatman = greatmanService.getGreatman(lowestLovedGreatmanScore.getId().intValue());
        jsonObject.put("lowest", lowestlovedGreatman.getName());//最不受该伟人待见
        jsonObject.put("lowest_lovescore", lowestLovedGreatmanScore.getScore());//最不受该伟人待见的亲密度
        jsonObject.put("greatman_count", ownedCount);//已召唤伟人数
        jsonObject.put("rank", "-");//排名超过玩家比例

        return success(jsonObject);
    }

    @GetMapping("/callGreatman")
    @Operation(summary = "召唤伟人")
    @Parameter(name = "greatmanId", description = "伟人ID", required = true, example = "1024")
    public CommonResult<GreatmanScore> callGreatman(@RequestParam("greatmanId") Long greatmanId) {
        GreatmanScore greatmanScore = userService.getGreatmanScore(getLoginUid(), greatmanId);
        if (greatmanScore.isOwned()) {
            throw exception(GREATMAN_HAS_OWNED);
        }
        if (greatmanScore.getScore() < 50) {
            throw exception(GREATMAN_SCORE_NOT_ENOUGH);
        }
        greatmanScore = userService.callGreatman(getLoginUid(), greatmanId);
        return success(greatmanScore);
    }

    public static void main(String[] args) {
        List<GreatmanScore> greatmenList = new ArrayList<>();

        // 添加一些Greatman对象到列表中
        greatmenList.add(new GreatmanScore(1L, 85, true));
        greatmenList.add(new GreatmanScore(2L, 92, false));
        greatmenList.add(new GreatmanScore(3L, 78, true));

        // 使用Java Stream找到score最大的Greatman对象
        GreatmanScore maxScoreGreatman = greatmenList.stream()
                .max(Comparator.comparingInt(GreatmanScore::getScore))
                .orElseThrow(NoSuchElementException::new);

        // 输出找到的结果
        System.out.println("Score 最大的 Greatman:");
        System.out.println("ID: " + maxScoreGreatman.getId());
        System.out.println("isowned: " + maxScoreGreatman.isOwned());
        System.out.println("Score: " + maxScoreGreatman.getScore());
        System.out.println("count: " + greatmenList.stream().filter(GreatmanScore::isOwned).count());

    }
}
